<template>
    <div class="bg-white m-4 mr-0 overflow-hidden">
        <BasicTree
                v-if="!treeReloading"
                title="树表管理列表"
                search
                showLine
                :checkStrictly="true"
                :clickRowToExpand="false"
                :treeData="treeData"
                :selectedKeys="selectedKeys"
                :expandedKeys="expandedKeys"
                :autoExpandParent="autoExpandParent"
                :actionList="actionList"
                @select="onSelect"
                @expand="onExpand"
                @search="loadTreeData"
        />
    </div>
    <TreeModal @register="registerModal" @success="handleSuccess" />
</template>

<script lang="ts" setup>
    import { inject, nextTick, ref, h } from 'vue';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { BasicTree, ActionItem } from '/@/components/Tree';
    import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
    import { loadTree,getById, deleteById } from '../tree.api';
    import TreeModal from '../TreeModal.vue';
    import { useModal } from '/@/components/Modal';

    const emit = defineEmits(['select']);
    const { createMessage } = useMessage();

    const [registerModal, { openModal }] = useModal();

    let loading = ref<boolean>(false);
    // 树表管理树列表数据
    let treeData = ref<any[]>([]);
    // 当前展开的项
    let expandedKeys = ref<any[]>([]);
    // 当前选中的项
    let selectedKeys = ref<any[]>([]);
    // 是否自动展开父级
    let autoExpandParent = ref<boolean>(true);
    // 树组件重新加载
    let treeReloading = ref<boolean>(false);

    function handleAddSub(node: any) {
        let record = {
            parentId: null
        };
        record.parentId = node.id;
        openModal(true, {
            record:record,
            isUpdate: false,
        });
    }

    async function handleEdit(node: any) {
        let record = await  getById({ id: node.id });
        openModal(true, {
            record:record,
            isUpdate: true,
        });
    }

    function handleDel(node: any) {
        deleteById({ id: node.id },reloadTree)
    }

    /**
     * 成功回调
     */
    function handleSuccess() {
        console.log('成功回调!');
    }

    const actionList: ActionItem[] = [
        {
            // show:()=>boolean;
            //新增
            render: (node) => {
                return h(PlusOutlined, {
                    // class: 'ml-2',
                    onClick: () => {
                        handleAddSub(node);
                    },
                });
            },
        },
        //编辑
        {
            render: (node) => {
                return h(EditOutlined, {
                    onClick: () => {
                        handleEdit(node);
                    },
                });
            },
        },
        //删除
        {
            render: (node) => {
                return h(DeleteOutlined, {
                    onClick: () => {
                        handleDel(node);
                    },
                });
            },
        },
    ];


    // 搜索事件&&加载树信息
    function loadTreeData(value?: string) {
        let params = {}
        if (value) {
            loading.value = true;
             params = {title:value}
        }
        loadTree(params)
        .then((result) => {
            if (Array.isArray(result)) {
                treeData.value = result;
            } else {
                createMessage.warning('未查询到树表管理信息');
                treeData.value = [];
            }
        })
        .finally(() => (loading.value = false));
    }

    loadTreeData();

    // 自动展开父节点，只展开一级
    function autoExpandParentNode() {
        let keys: Array<any> = [];
        treeData.value.forEach((item, index) => {
            if (item.children && item.children.length > 0) {
                keys.push(item.key);
            }
            if (index === 0) {
                // 默认选中第一个
                setSelectedKey(item.id, item);
            }
        });
        if (keys.length > 0) {
            reloadTree();
            expandedKeys.value = keys;
        }
    }

    // 重新加载树组件，防止无法默认展开数据
    async function reloadTree() {
        await nextTick();
        treeReloading.value = true;
        await nextTick();
        treeReloading.value = false;
    }

    /**
     * 设置当前选中的行
     */
    function setSelectedKey(key: string, data?: object) {
        selectedKeys.value = [key];
        if (data) {
            emit('select', data);
        }
    }



    // 树选择事件
    function onSelect(selKeys, event) {
        if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
            setSelectedKey(selKeys[0], event.selectedNodes[0]);
        } else {
            // 这样可以防止用户取消选择
            setSelectedKey(selectedKeys.value[0]);
        }
    }

    // 树展开事件
    function onExpand(keys) {
        expandedKeys.value = keys;
        autoExpandParent.value = false;
    }

    defineExpose({
        loadTreeData,
    });
</script>
<style lang="less" scoped>
    /*升级antd3后，查询框与树贴的太近，样式优化*/
    :deep(.jeecg-tree-header) {
        margin-bottom: 6px;
    }
</style>

